/*
 * @Author: 刘经标 2604132672@qq.com
 * @Date: 2025-04-15 10:16:57
 * @LastEditors: 刘经标 2604132672@qq.com
 * @LastEditTime: 2025-05-09 17:52:23
 * @FilePath: /ai-assistant-frontend/src/components/Message.tsx
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { Avatar, Box, Paper, Typography, Button } from '@mui/material';
import { Face as UserIcon, SmartToy as BotIcon, LocationOn, Map as MapIcon } from '@mui/icons-material';
import { useState } from 'react';
import { ImagePreview } from './ImagePreview';
import { getStaticMapUrl } from '../services/amap';

interface MessageProps {
  content: string;
  isUser: boolean;
  timestamp: Date;
  quotedMessage?: {
    content: string;
    timestamp: Date;
  };
  image?: {
    url: string;
    filename: string;
  };
  location?: {
    latitude: number;
    longitude: number;
    address: string;
    businessAreas?: string;
  };
  onLongPress?: (event: React.MouseEvent) => void;
}

export const Message: React.FC<MessageProps> = ({
  content,
  isUser,
  timestamp,
  quotedMessage,
  image,
  location,
  onLongPress
}) => {
  const [isImagePreviewOpen, setIsImagePreviewOpen] = useState(false);

  const handleLocationClick = () => {
    alert('您的浏览器不支持地理位置功能');
    if (location) {
      // 尝试使用不同的URI格式 - 高德地图Web版直接链接
      const url = `https://www.amap.com/?q=${location.latitude},${location.longitude}&query=${encodeURIComponent(location.address)}`;
      console.log('正在打开地图URL:', url);
      window.open(url, '_blank');
    }
  };

  return (
    <Box
      sx={{
        display: 'flex',
        alignItems: 'flex-start',
        justifyContent: isUser ? 'flex-end' : 'flex-start',
        mb: 2,
        position: 'relative',
      }}
      onContextMenu={(e) => {
        e.preventDefault();
        onLongPress?.(e);
      }}
    >
      {!isUser && (
        <Avatar
          sx={{
            bgcolor: 'primary.main',
            width: 32,
            height: 32,
            mr: 1
          }}
        >
          <BotIcon fontSize="small" />
        </Avatar>
      )}
      
      <Paper
        sx={{
          maxWidth: '70%',
          p: 2,
          backgroundColor: isUser ? 'primary.main' : 'grey.100',
          color: isUser ? 'white' : 'text.primary',
          borderRadius: 2,
        }}
      >
        {quotedMessage && (
          <Box
            sx={{
              borderLeft: '4px solid',
              borderColor: isUser ? 'rgba(255,255,255,0.5)' : 'primary.main',
              pl: 1,
              mb: 1,
              py: 0.5,
              backgroundColor: isUser ? 'rgba(255,255,255,0.1)' : 'rgba(0,0,0,0.05)',
              borderRadius: '4px',
            }}
          >
            <Typography 
              variant="body2" 
              sx={{ 
                color: isUser ? 'rgba(255,255,255,0.7)' : 'text.secondary',
                fontSize: '0.85rem',
                whiteSpace: 'nowrap',
                overflow: 'hidden',
                textOverflow: 'ellipsis',
                maxWidth: '100%'
              }}
            >
              {quotedMessage.content}
            </Typography>
          </Box>
        )}
        
        {image && (
          <>
            <Box sx={{ mb: 1 }}>
              <img 
                src={image.url} 
                alt={image.filename}
                style={{
                  maxWidth: '100%',
                  maxHeight: 300,
                  borderRadius: 4,
                  cursor: 'pointer',
                  objectFit: 'cover'
                }}
                onClick={() => setIsImagePreviewOpen(true)}
              />
            </Box>
            <ImagePreview
              url={image.url}
              isOpen={isImagePreviewOpen}
              onClose={() => setIsImagePreviewOpen(false)}
            />
          </>
        )}
        
        <Typography sx={{ wordBreak: 'break-word' }}>{content}</Typography>
        
        {location && (
          <Button
            variant="outlined"
            size="small"
            startIcon={<MapIcon />}
            sx={{ 
              mt: 1,
              fontSize: '0.75rem', 
              textTransform: 'none',
              color: isUser ? 'white' : 'primary.main',
              borderColor: isUser ? 'rgba(255,255,255,0.5)' : 'primary.main',
              '&:hover': {
                borderColor: isUser ? 'white' : 'primary.dark',
                backgroundColor: isUser ? 'rgba(255,255,255,0.1)' : 'rgba(25, 118, 210, 0.04)'
              }
            }}
            onClick={() => {
              if (location) {
                const url = `https://www.amap.com/?q=${location.latitude},${location.longitude}&query=${encodeURIComponent(location.address)}`;
                window.open(url, '_blank');
              }
            }}
          >
            查看位置
          </Button>
        )}
        
        <Typography 
          variant="caption" 
          sx={{ 
            display: 'block',
            mt: 0.5,
            color: isUser ? 'rgba(255,255,255,0.7)' : 'text.secondary',
          }}
        >
          {new Date(timestamp).toLocaleTimeString()}
        </Typography>
      </Paper>

      {isUser && (
        <Avatar
          sx={{
            bgcolor: 'primary.main',
            width: 32,
            height: 32,
            ml: 1
          }}
        >
          <UserIcon fontSize="small" />
        </Avatar>
      )}
    </Box>
  );
};